package demo.huodongbaoming.service.impl;

import demo.huodongbaoming.dto.ActivityDTO;
import demo.huodongbaoming.dto.ActivityRequest;
import demo.huodongbaoming.entity.Activity;
import demo.huodongbaoming.entity.ActivityCategory;
import demo.huodongbaoming.entity.User;
import demo.huodongbaoming.repository.ActivityRepository;
import demo.huodongbaoming.service.ActivityService;
import demo.huodongbaoming.service.CategoryService;
import demo.huodongbaoming.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityNotFoundException;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ActivityServiceImpl implements ActivityService {

    @Autowired
    private ActivityRepository activityRepository;

    @Autowired
    private UserService userService;
    
    @Autowired
    private CategoryService categoryService;

    @Override
    @Transactional
    public ActivityDTO createActivity(ActivityRequest activityRequest, Long creatorId) {
        // 获取创建者
        User creator = userService.getUserEntityById(creatorId);

        // 创建活动
        Activity activity = new Activity();
        BeanUtils.copyProperties(activityRequest, activity);
        activity.setCreator(creator);
        activity.setCurrentParticipants(0);
        activity.setActive(true);
        
        // 设置活动类别
        if (activityRequest.getCategoryId() != null) {
            ActivityCategory category = categoryService.getCategoryById(activityRequest.getCategoryId());
            activity.setCategory(category);
        }

        // 保存活动
        Activity savedActivity = activityRepository.save(activity);

        // 转换为DTO并返回
        return convertToDTO(savedActivity);
    }

    @Override
    @Transactional(readOnly = true)
    public ActivityDTO getActivityById(Long id) {
        Activity activity = activityRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("活动不存在"));
        return convertToDTO(activity);
    }

    @Override
    @Transactional(readOnly = true)
    public List<ActivityDTO> getAllActivities() {
        return activityRepository.findAll().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(readOnly = true)
    public List<ActivityDTO> getActiveActivities() {
        List<Activity> activities = activityRepository.findByIsActiveTrue();
        return activities.stream()
                .map(activity -> {
                    // 提前访问懒加载属性
                    if (activity.getCreator() != null) {
                        activity.getCreator().getName();
                    }
                    if (activity.getCategory() != null) {
                        activity.getCategory().getName();
                    }
                    return convertToDTO(activity);
                })
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(readOnly = true)
    public List<ActivityDTO> getActivitiesByCreator(Long creatorId) {
        User creator = userService.getUserEntityById(creatorId);
        List<Activity> activities = activityRepository.findByCreator(creator);
        return activities.stream()
                .map(activity -> {
                    // 提前访问懒加载属性
                    if (activity.getCategory() != null) {
                        activity.getCategory().getName();
                    }
                    return convertToDTO(activity);
                })
                .collect(Collectors.toList());
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<ActivityDTO> getActivitiesByCategory(Long categoryId) {
        ActivityCategory category = categoryService.getCategoryById(categoryId);
        List<Activity> activities = activityRepository.findByCategory(category);
        return activities.stream()
                .map(activity -> {
                    // 提前访问懒加载属性
                    if (activity.getCreator() != null) {
                        activity.getCreator().getName();
                    }
                    return convertToDTO(activity);
                })
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public ActivityDTO updateActivity(Long id, ActivityRequest activityRequest) {
        Activity activity = activityRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("活动不存在"));

        // 更新活动信息
        activity.setTitle(activityRequest.getTitle());
        activity.setDescription(activityRequest.getDescription());
        activity.setStartTime(activityRequest.getStartTime());
        activity.setEndTime(activityRequest.getEndTime());
        activity.setRegistrationDeadline(activityRequest.getRegistrationDeadline());
        activity.setLocation(activityRequest.getLocation());
        activity.setMaxParticipants(activityRequest.getMaxParticipants());
        activity.setCoverImage(activityRequest.getCoverImage());
        
        // 更新活动状态
        if (activityRequest.getIsActive() != null) {
            activity.setActive(activityRequest.getIsActive());
        }
        
        // 更新类别
        if (activityRequest.getCategoryId() != null) {
            ActivityCategory category = categoryService.getCategoryById(activityRequest.getCategoryId());
            activity.setCategory(category);
        }

        // 保存更新
        Activity updatedActivity = activityRepository.save(activity);

        // 转换为DTO并返回
        return convertToDTO(updatedActivity);
    }

    @Override
    @Transactional
    public void deleteActivity(Long id) {
        Activity activity = activityRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("活动不存在"));
        
        // 逻辑删除，将活动设为不活跃
        activity.setActive(false);
        activityRepository.save(activity);
    }

    @Override
    @Transactional
    public ActivityDTO registerForActivity(Long activityId, Long userId) {
        Activity activity = activityRepository.findById(activityId)
                .orElseThrow(() -> new EntityNotFoundException("活动不存在"));
        User user = userService.getUserEntityById(userId);

        // 检查活动是否已满
        if (activity.getMaxParticipants() != null && 
            activity.getCurrentParticipants() >= activity.getMaxParticipants()) {
            throw new RuntimeException("活动已满，无法报名");
        }

        // 检查用户是否已报名
        if (user.getRegisteredActivities().contains(activity)) {
            throw new RuntimeException("您已报名该活动");
        }

        // 报名活动
        user.getRegisteredActivities().add(activity);
        activity.getParticipants().add(user);
        activity.setCurrentParticipants(activity.getCurrentParticipants() + 1);

        // 保存更新
        Activity updatedActivity = activityRepository.save(activity);

        // 转换为DTO并返回
        return convertToDTO(updatedActivity);
    }

    @Override
    @Transactional
    public ActivityDTO cancelRegistration(Long activityId, Long userId) {
        Activity activity = activityRepository.findById(activityId)
                .orElseThrow(() -> new EntityNotFoundException("活动不存在"));
        User user = userService.getUserEntityById(userId);

        // 检查用户是否已报名
        if (!user.getRegisteredActivities().contains(activity)) {
            throw new RuntimeException("您未报名该活动");
        }

        // 取消报名
        user.getRegisteredActivities().remove(activity);
        activity.getParticipants().remove(user);
        activity.setCurrentParticipants(activity.getCurrentParticipants() - 1);

        // 保存更新
        Activity updatedActivity = activityRepository.save(activity);

        // 转换为DTO并返回
        return convertToDTO(updatedActivity);
    }

    @Override
    @Transactional(readOnly = true)
    public List<ActivityDTO> getRegisteredActivities(Long userId) {
        User user = userService.getUserEntityById(userId);
        return user.getRegisteredActivities().stream()
                .map(activity -> {
                    // 提前访问懒加载属性
                    if (activity.getCreator() != null) {
                        activity.getCreator().getName();
                    }
                    if (activity.getCategory() != null) {
                        activity.getCategory().getName();
                    }
                    return convertToDTO(activity);
                })
                .collect(Collectors.toList());
    }
    
    @Override
    @Transactional
    public ActivityDTO updateActivityStatus(Long id, boolean isActive) {
        Activity activity = activityRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("活动不存在"));
        
        activity.setActive(isActive);
        Activity updatedActivity = activityRepository.save(activity);
        
        return convertToDTO(updatedActivity);
    }

    private ActivityDTO convertToDTO(Activity activity) {
        ActivityDTO activityDTO = new ActivityDTO();
        BeanUtils.copyProperties(activity, activityDTO);
        
        // 设置创建者信息
        if (activity.getCreator() != null) {
            activityDTO.setCreatorId(activity.getCreator().getId());
            activityDTO.setCreatorName(activity.getCreator().getName() != null ? 
                    activity.getCreator().getName() : "");
        }
        
        // 设置类别信息
        if (activity.getCategory() != null) {
            activityDTO.setCategoryId(activity.getCategory().getId());
            activityDTO.setCategoryName(activity.getCategory().getName() != null ? 
                    activity.getCategory().getName() : "");
        }
        
        return activityDTO;
    }
} 